var localStorage = cc.sys.localStorage;
window.gameData = window.gameData || {};
var compareTwoNumbers = function (a, b) {
    return a - b
};

var equleTo0 = function (n) {
    return n == 0;
};

var getCurTimestamp = function () {
    return Math.round((new Date()).getTime() / 1000);
};

var time2timestamp = function (time) {

};

var getPaiLR = function (paiId) {
    if (paiId >= 1 && paiId <= 9)
        return [1, 9];
    if (paiId >= 10 && paiId <= 18)
        return [10, 18];
    if (paiId >= 19 && paiId <= 27)
        return [19, 27];
    return null;
};

var isSameColor = function (paiIdA, paiIdB) {
    if (paiIdA >= 1 && paiIdA <= 9)
        return paiIdB >= 1 && paiIdB <= 9;
    if (paiIdA >= 10 && paiIdA <= 18)
        return paiIdB >= 10 && paiIdB <= 18;
    if (paiIdA >= 19 && paiIdA <= 27)
        return paiIdB >= 19 && paiIdB <= 27;
    if (paiIdA >= 28 && paiIdA <= 34)
        return paiIdB >= 28 && paiIdB <= 34;
    return false;
};

var timestamp2time = function (timestamp, format) {
    format = format || "yyyy-mm-dd HH:MM:ss";
    var date = new Date(parseInt(timestamp) * 1000);
    return dateFormat(date, format);
};

var vibrate = function () {
    if (cc.sys.os == cc.sys.OS_IOS)
        cc.Device.vibrate(1);
    else if (cc.sys.os == cc.sys.OS_ANDROID) {
        cc.Device.vibrate(1);
    }
};

var regBakBtn = function () {
    if (cc.sys.os == cc.sys.OS_ANDROID) {
        cc.eventManager.addListener({
            event: cc.EventListener.KEYBOARD, onKeyReleased: function (keyCode, event) {
                if (keyCode == cc.KEY.back) {
                    if (cc.director.getRunningScene().getChildByName('alertLayer')) {
                        cc.director.getRunningScene().getChildByName('alertLayer').removeFromParent(true);
                    } else {
                        alert2('确定退出游戏吗?', function () {
                            cc.director.end();
                        }, null, false, true, true);
                    }
                }
                else if (keyCode == cc.KEY.menu) {

                }
            }
        }, this);
    }
};

var getBatteryLevel = function () {
    var level = "100";
    if (cc.sys.os == cc.sys.OS_IOS) {
        level = jsb.reflection.callStaticMethod(
            "AppController",
            "getBatteryLevel"
        );
    }
    // else if (cc.sys.os == cc.sys.OS_ANDROID) {
    //     level = jsb.reflection.callStaticMethod(
    //         "org/cocos2dx/javascript/AppActivity",
    //         "getBatteryLevel",
    //         "()Ljava/lang/String;"
    //     );
    // }
    return Math.floor(Number(level));
};

var playAnimScene = function (distNode, res, posx, posy, loop) {
    var cacheNode = distNode.getChildByName(res);
    if (!cacheNode) {
        var animScene = ccs.load(res);
        cacheNode = animScene.node;
        cacheNode.setName(res);
        distNode.addChild(cacheNode);
        cacheNode.runAction(animScene.action);
        cacheNode.setPosition(posx, posy);

        var userdata = cacheNode.getUserData() || {};
        userdata.action = animScene.action;
        cacheNode.setUserData(userdata);
    }

    var userdata = cacheNode.getUserData();
    userdata.action.play('action', loop);
    return cacheNode;
};

var getPaiLR = function (paiId) {
    var t = [1, 9, 10, 18, 19, 27];
    var a = 0, b = 0;
    for (var i = 0; i < t.length; i += 2) {
        var l = t[i];
        var r = t[i + 1];
        if (paiId >= l && paiId <= r) {
            a = l;
            b = r;
            break;
        }
    }
    return {l: a, r: b};
};

var ellipsisStr = function (str, n) {
    if (str.length > n)
        str = str.substr(0, n - 1) + '..';
    return str;
};

var playMusic = (function () {
    return function (filename, isRepeate, enforce) {
        // filename = 'vbg';
        if (!cc.sys.isNative)
            return;
        if (!isRepeate) {
            isRepeate = true;
        }
        if (gameData && gameData.voiceFlag == false) {
            return;
        }
        if (window.curBg == filename && !enforce)
            return;
        window.curBg = filename;
        if (!_.isUndefined(window.musicID)) {
            jsb.AudioEngine.stop(window.musicID);
            window.musicID = null;
        }
        var t = filename;
        if (_.isUndefined(window.musicVolume)) {
            resetVolume();
        }
        if (res[t]) {
            window.musicID = jsb.AudioEngine.play2d(res[t], isRepeate, window.musicVolume);
        } else if (res[filename]) {
            window.musicID = jsb.AudioEngine.play2d(res[filename], isRepeate, window.musicVolume);
        } else {
            cc.log("sound not found: " + filename);
        }
    }
})();

var pauseMusic = function () {
    if (!cc.sys.isNative) {
        return;
    }
    if (!_.isUndefined(window.musicID)) {
        jsb.AudioEngine.pause(window.musicID);
    }
};

var resumeMusic = function () {
    if (!cc.sys.isNative) {
        return;
    }
    if (!_.isUndefined(window.musicID)) {
        jsb.AudioEngine.resume(window.musicID);
    } else {
        playMusic();
    }
};

var stopMusic = function () {
    if (!cc.sys.isNative) {
        return;
    }
    if (!_.isUndefined(window.musicID)) {
        jsb.AudioEngine.stop(window.musicID);
        window.musicID = null;
    }
};

var resetVolume = function () {
    if (!cc.sys.isNative) {
        return;
    }
    resetMusicVolume();
    resetEffectVolume();
};

var resetMusicVolume = function () {
    if (!cc.sys.isNative) {
        return;
    }
    if (cc.sys.os == cc.sys.OS_ANDROID) {
        window.musicVolume = (cc.sys.localStorage.getItem('yinyuePrecent') || 1) / 300;
    } else {
        window.musicVolume = (cc.sys.localStorage.getItem('yinyuePrecent') || 1) / 1000;
    }
    if (window.musicID || window.musicID == 0) {
        jsb.AudioEngine.setVolume(window.musicID, window.musicVolume);
    }
};

var resetEffectVolume = function () {
    if (!cc.sys.isNative) {
        return;
    }
    // if (cc.sys.os == cc.sys.OS_ANDROID) {
    //     window.effectVolume = (cc.sys.localStorage.getItem('yinxiaoPrecent') || 1) / 200;
    // } else {
    //     window.effectVolume = (cc.sys.localStorage.getItem('yinxiaoPrecent') || 1) / 800;
    // }
    window.effectVolume = (cc.sys.localStorage.getItem('yinxiaoPrecent') || 1)
};

var muteVolume = function () {
    if (!cc.sys.isNative) {
        return;
    }
    jsb.AudioEngine.stopAll();
};

var playEffect = function (filename, sex) {
    if (!gameData)
        return;
    if (gameData && gameData.voiceFlag == false) {
        return;
    }
    if (_.isUndefined(window.effectVolume)) {
        resetVolume();
    }
    var t = filename + '_' + (typeof sex === 'undefined' ? gameData.sex : sex);
    var soundRes = res;
    var soundName = soundRes[t] || soundRes[filename] || res[t] || res[filename];
    if (_.isArray(soundName)) {
        soundName = soundName[Math.floor(Math.random() * soundName.length)]
    }
    if (!soundName) {
        cc.log("sound not found: " + filename);
        return;
    }
    if (!cc.sys.isNative) {
        cc.audioEngine.playEffect(soundName, false);
    } else {
        jsb.AudioEngine.play2d(soundName, false, window.effectVolume);
    }
};

var playNorEffect = function (filename) {
    // if (!cc.sys.isNative) {
    //     return;
    // }
    var volume = 1;
    if (cc.sys.os == cc.sys.OS_ANDROID) {
        volume = 1.5;
    }
    if (!cc.sys.isNative) {
        cc.audioEngine.playEffect(filename, false);
    } else {
        // cc.log("filename=="+filename)
        jsb.AudioEngine.play2d(filename, false, volume);
    }
};

var captureAndShareToWX = function (node, a) {
    var winSize = cc.director.getWinSize();
    var texture = new cc.RenderTexture(winSize.width, winSize.height, null, a);
    if (!texture)
        return;

    texture.retain();

    texture.setAnchorPoint(0, 0);
    texture.begin();
    node.visit();
    texture.end();

    var time = timestamp2time(Math.round((new Date()).valueOf() / 1000));
    time = time.replace(/[\s:-]+/g, '_');
    var namePNG = "ss-" + time + ".png";
    var nameJPG = "ss-" + time + ".jpg";

    if (cc.sys.os == cc.sys.OS_ANDROID) {
        texture.saveToFile(nameJPG, cc.IMAGE_FORMAT_JPEG, false, function (renderTexture, str) {
            texture.release();
            jsb.reflection.callStaticMethod(
                "org/cocos2dx/javascript/AppActivity",
                "sharePic",
                "(Ljava/lang/String;Z)V",
                nameJPG,
                false
            );
        });
    }
    else if (cc.sys.os == cc.sys.OS_IOS) {
        texture.saveToFile(namePNG, cc.IMAGE_FORMAT_PNG, true, function (renderTexture, str) {
            texture.release();
            jsb.reflection.callStaticMethod(
                "AppController",
                "sharePic:imageName:sceneType:",
                jsb.fileUtils.getWritablePath(),
                namePNG,
                0
            );
        });
    }

};

var getNativeVersion = function () {
    if (!window.nativeVersion) {

        if (!cc.sys.isNative)
            return;
        if (cc.sys.os == cc.sys.OS_IOS) {
            window.nativeVersion = jsb.reflection.callStaticMethod(
                "AppController",
                "getVersionName"
            );
        }
        else {
            window.nativeVersion = jsb.reflection.callStaticMethod(
                "org/cocos2dx/javascript/AppActivity",
                "getVersionName",
                "()Ljava/lang/String;"
            );
        }
    }
    return window.nativeVersion;
};

var downloadAndInstallApk = function (url) {
    if (!cc.sys.isNative)
        return;
    if (cc.sys.os == cc.sys.OS_IOS) {
        return jsb.reflection.callStaticMethod(
            "org/cocos2dx/javascript/AppActivity",
            "getVersionName",
            "()Ljava/lang/String;"
        );
    }
};


var fetchUDID = function () {
    if (!cc.sys.isNative) {
        return "0123456789abcdef";
    }
    if (cc.sys.os == cc.sys.OS_IOS) {
        return jsb.reflection.callStaticMethod(
            "AppController",
            "fetchUDID"
        );
    }
    else {
        return jsb.reflection.callStaticMethod(
            "org/cocos2dx/javascript/AppActivity",
            "fetchUDID",
            "()Ljava/lang/String;"
        );
    }
};

var getNextIp = function () {
    if (!cc.sys.isNative) {
        return null;
    }
    if (cc.sys.os == cc.sys.OS_IOS) {
        try {
            return jsb.reflection.callStaticMethod(
                "AppController",
                "ni"
            );
        } catch (e) {
            console.log(e.toString());
        }
    }
    else {
        return jsb.reflection.callStaticMethod(
            "org/cocos2dx/javascript/AppActivity",
            "ni",
            "()Ljava/lang/String;"
        );
    }
};

var getNextIp2 = function (group, sk) {
    group = group || "hnpk1.X23SX9y72m.aliyungf.com";

    if (!cc.sys.isNative) {
        return null;
    }
    if (cc.sys.os == cc.sys.OS_IOS) {
        try {
            return jsb.reflection.callStaticMethod(
                "AppController",
                "ni2:n:",
                YunCengKey_ios,
                group
            );
        } catch (e) {
        }
    }
    else {
        return jsb.reflection.callStaticMethod(
            "org/cocos2dx/javascript/AppActivity",
            "ni2",
            "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;",
            YunCengKey_android,
            group
        );
    }
};

String.prototype.hashCode = function() {
    var hash = 0, i, chr;
    if (this.length === 0) return hash;
    for (i = 0; i < this.length; i++) {
        chr   = this.charCodeAt(i);
        hash  = ((hash << 5) - hash) + chr;
        hash |= 0; // Convert to 32bit integer
    }
    return hash;
};

var hosts = [
    "qq.073dk9bhyovh.life",
    "qq.0hass9we5dla.life",
    "qq.10o39o4ojcq8.life",
    "qq.1327lywax9se.life",
    "qq.1gj8e0foecpj.life",
    "qq.185jbs3p5gdo.life",
    "qq.1k99f4ttvyvc.life",
    "qq.1kjn0k60vw5d.life",
    "qq.1qv23j3kfiyw.life",
    "qq.1ruqwp5xgx34.life",
    "qq.20oq26bdnsfo.life",
    "qq.22lut2ivmb07.life",
    "qq.2qopvgtp2tve.life",
    "qq.2y96rwfp309a.life",
    "qq.2zn6swt6un1n.life",
    "qq.33onivavt060.life",
    "qq.3ncafyn2gk77.life",
    "qq.4im3h10hilwv.life",
    "qq.4xy3vsdg9dev.life",
    "qq.4xgeo6inu9xq.life",
    "qq.593c37ylnygj.life",
    "qq.5es2k22cwc05.life",
    "qq.5jdvgi9ebwby.life",
    "qq.6croxz5e8psw.life",
    "qq.6j0nbix00vph.life",
    "qq.6mmbeyn39565.life",
    "qq.73y2b0tpowm5.life",
    "qq.7ainf05xkr08.life",
    "qq.7fda7m3lala7.life",
    "qq.7am9ers75pk8.life",
    "qq.8bbs7xj8em0e.life",
    "qq.9r8vaglnrrke.life",
    "qq.9sgfmfd9qvp0.life",
    "qq.9vawdamnuppo.life",
    "qq.a3711i5q2xja.life",
    "qq.abjtefuzd5vu.life",
    "qq.av8pnvwo89vd.life",
    "qq.b32bibkbg0jd.life",
    "qq.btnjp7lo0x1x.life",
    "qq.bc06ysj3vxj6.life",
    "qq.ce0d6d6o8ewm.life",
    "qq.d2w3ca8kv15d.life",
    "qq.d3jkucq5illw.life",
    "qq.e8ronbzu8uy6.life",
    "qq.ej7wia8vxsb1.life",
    "qq.edhc76d5v8ob.life",
    "qq.en6p02wsumn9.life",
    "qq.f2or3fyqkh6y.life",
    "qq.ezag6vgrxkjy.life",
    "qq.f79noc5xgsf1.life",
];
var getIpList = (function () {
    return function (udid) {
        udid = udid || "0";
        var ipList = [];
        var second = hosts[Math.abs(udid.hashCode()) % hosts.length];
        var third = 'poker.yygameapi.com';
         if (!window.inReview) {
            var sdkIp="";
            if(getNativeVersion()<"2.5.0"){
                sdkIp= getNextIp3();
            }else {
                sdkIp= getNextIp2();
            }
             ipList.push(sdkIp);
        }
        ipList.push(second);
        ipList.push(third);
        return ipList;
    }
})();


var getNextIp3 = function () {
    if (!cc.sys.isNative) {
        return null;
    }
    if (cc.sys.os == cc.sys.OS_IOS) {
        try {
            return jsb.reflection.callStaticMethod(
                "AppController",
                "ni2:n:",
                "aIllmg6BQuQfi0nYS59BsAlx+m+nhz-JQx7bMPrE+x2INaOSQESeDq-9RMpGDh2uzr-HISE1jgecwKcrgy61Pv_+Cbcyr2YIwK+8F-2ev15apqyNpHUwG1MN7ETEgz3l7urfUcMj1WVDfTzOlQxgQ_CMFEnzgwyDFRMN1GIepIxUDYnUq1+y5lTNX9RgkZPaBPuv+FilyikQxZwyiTCCSjCEAwCvq4RTApksUwJi8I2SaCLvlpVM9kqHzwFZvulqmNM2GUsVhQjph5hmwnKW3HtwEXNRoQvemZehZyPUfz4Ml_iZXQZoFputNFMNIdmm7Lug86gguAY582kFJwMM7lUEn6UB",
                "l2.j35264juy5.aliyungf.com," + window.udid
            );
        } catch (e) {
            console.log(e.toString());
        }
    }
    else {
        return jsb.reflection.callStaticMethod(
            "org/cocos2dx/javascript/AppActivity",
            "ni2",
            "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;",
            "aIllmg6BQuQfi0nYS59BsAlx+m+nhz-JQx7bMPrE+x2INaOSQESeDq-9RMpGDh2uzr-HISE1jgecwKcrgy61Pv_+Cbcyr2YIwK+8F-2ev15apqyNpHUwG1MN7ETEgz3l7urfUcMj1WVDfTzOlQxgQ_CMFEnzgwyDFRMN1GIepIxUDYnUq1+y5lTNX9RgkZPaBPuv+FilyikQxZwyiTCCSjCEAwCvq4RTApksUwJi8I2SaCLvlpVM9kqHzwFZvulqmNM2GUsVhQjph5hmwnKW3HtwEXNRoQvemZehZyPUfz4Ml_iZXQZoFputNFMNIdmm7Lug86gguAY582kFJwMM7lUEn6UB",
            "l2.j35264juy5.aliyungf.com," + window.udid
        );
    }
};


var startLocate = function () {
    if (!cc.sys.isNative) {
        return null;
    }
    if (cc.sys.os == cc.sys.OS_IOS) {
        return jsb.reflection.callStaticMethod(
            "AppController",
            "startLocate"
        );
    }
    else {
        return jsb.reflection.callStaticMethod(
            "org/cocos2dx/javascript/AppActivity",
            "startLocate",
            "()Ljava/lang/String;"
        );
    }
};

var getCurLocation = function () {
    if (!cc.sys.isNative) {
        return null;
    }
    if (cc.sys.os == cc.sys.OS_IOS) {
        return jsb.reflection.callStaticMethod(
            "AppController",
            "getCurLocation"
        );
    }
    else {
        return jsb.reflection.callStaticMethod(
            "org/cocos2dx/javascript/AppActivity",
            "getCurLocation",
            "()Ljava/lang/String;"
        );
    }
};

var clearCurLocation = function () {
    if (!cc.sys.isNative) {
        return null;
    }
    if (cc.sys.os == cc.sys.OS_IOS) {
        return jsb.reflection.callStaticMethod(
            "AppController",
            "clearCurLocation"
        );
    }
    else {
        return jsb.reflection.callStaticMethod(
            "org/cocos2dx/javascript/AppActivity",
            "clearCurLocation",
            "()Ljava/lang/String;"
        );
    }
};

var setSpriteFrameByName = function (sprite, name, plist, plistpath) {
    for (var i = 0; i < 3; i++) {
        var frame = cc.spriteFrameCache.getSpriteFrame(name);
        if (!frame) {
            if (plistpath) {
                cc.spriteFrameCache.addSpriteFrames(plistpath);
            } else {
                cc.spriteFrameCache.addSpriteFrames('res/anim/' + plist + '.plist');
            }
        } else {
            sprite.setSpriteFrame(frame);
            return;
        }
    }
    if (!cc.sys.isNative)
        throw new Error("getSpriteFrame(" + name + ") == null");
    else
        alert1("getSpriteFrame(" + name + ") == null");
};

var setPokerFrameByName = function (sprite, name) {
    var frame = cc.spriteFrameCache.getSpriteFrame(name);
    if (!frame) {
        cc.spriteFrameCache.addSpriteFrames('res/ui/resources/card/poker_b.plist');
    }
    sprite.setSpriteFrame(frame);
};
var setPokerFrameByNameNN = function (sprite, name) {
    if (name == null || name == undefined) {
        sprite.setVisible(false);
        return;
    }
    for (var i = 0; i < 3; i++) {
        var frame = cc.spriteFrameCache.getSpriteFrame(name);
        if (!frame) {
            cc.spriteFrameCache.addSpriteFrames('res/ui/resources/card/poker_b.plist');
        } else {
            sprite.setSpriteFrame(frame);
            return;
        }
    }
    if (!cc.sys.isNative)
        throw new Error("getSpriteFrame(" + name + ") == null");
    else
        alert1("getSpriteFrame(" + name + ") == null");
};
////1方片 2梅花 3红桃 4黑桃
var getBigCardName = function (id) {
    var name = "clubs_1.png";
    var huaseArr = ['diamonds', 'clubs', 'hearts', 'spades'];
    var huase = huaseArr[(id - 1) % 4];
    var id = Math.floor((id + 3) / 4);
    return huase + "_" + id + ".png";
};
var getBigCardJiaoName = function (id) {
    var name = "clubs_1.png";
    var huaseArr = ['diamonds', 'clubs', 'hearts', 'spades'];
    var huase = huaseArr[(id - 1) % 4];
    var id = Math.floor((id + 3) / 4);
    return huase + "_num_" + id + ".png";
};
var setUIImageFrameByName = function (sprite, name, plist) {
    if (name == null || name == undefined) {
        sprite.setVisible(false);
        return;
    }
    for (var i = 0; i < 3; i++) {
        var frame = cc.spriteFrameCache.getSpriteFrame(name);
        if (!frame) {
            cc.spriteFrameCache.addSpriteFrames('res/ui/resources/' + plist + '.plist');
        } else {
            sprite.loadTexture(name, ccui.Widget.PLIST_TEXTURE);
            return;
        }
    }
    if (!cc.sys.isNative)
        throw new Error("getSpriteFrame(" + name + ") == null");
    else
        alert1("getSpriteFrame(" + name + ") == null");
};
var playFrameAnim = function (plistFilePath, prefix, frameCnt, speed, isLoop, sprite, endCb) {
    playFrameAnim2(plistFilePath, prefix, 0, frameCnt, speed, isLoop, sprite, endCb);
};

var playFrameAnim2 = function (plistFilePath, prefix, beginFrame, frameCnt, speed, isLoop, sprite, endCb) {
    cc.spriteFrameCache.addSpriteFrames(plistFilePath);

    var animFrames = [];
    for (var i = beginFrame; i < beginFrame + frameCnt; i++) {
        var frame = cc.spriteFrameCache.getSpriteFrame(prefix + i + '.png');
        animFrames.push(frame);
    }
    var animation = new cc.Animation(animFrames, speed);

    var action = cc.animate(animation);
    sprite.stopAllActions();
    if (isLoop) {
        sprite.runAction(action.repeatForever());
    }
    else {
        sprite.runAction(cc.sequence(action, cc.callFunc(function () {
            if (endCb)
                endCb();
        })));
    }
};
var playFrameAnim3 = function (plistFilePath, prefix, frameCnt, speed, time, sprite1, sprite2, endCb) {
    cc.spriteFrameCache.addSpriteFrames(plistFilePath);

    var animFrames = [];
    for (var i = 0; i < 0 + frameCnt; i++) {
        var frame = cc.spriteFrameCache.getSpriteFrame(prefix + i + '.png');
        animFrames.push(frame);
    }
    var animation1 = new cc.Animation(animFrames, speed);
    var animation2 = new cc.Animation(animFrames, speed);

    var action1 = cc.animate(animation1);
    var action2 = cc.animate(animation2);
    sprite1.stopAllActions();
    sprite2.stopAllActions();
    sprite1.runAction(action1.repeatForever());
    sprite2.runAction(action2.repeatForever());
    setTimeout(function () {
        sprite1.stopAllActions();
        sprite2.stopAllActions();
        if (endCb)
            endCb();
    }, time);

};

var shareText = function (text, sceneType, transaction) {
    if (!cc.sys.isNative) {
        return;
    }
    if (getNativeVersion() < '1.4.0') {
        if (cc.sys.os == cc.sys.OS_IOS) {
            jsb.reflection.callStaticMethod(
                "AppController",
                "shareText:sceneType:",
                text,
                (sceneType ? 1 : 0)
            );
        }
        else {
            jsb.reflection.callStaticMethod(
                "org/cocos2dx/javascript/AppActivity",
                "shareText",
                "(Ljava/lang/String;ZLjava/lang/String;)V",
                text,
                (sceneType ? true : false),
                transaction
            );
        }
    } else {
        WXUtils.shareText(text, sceneType, transaction);
    }
};

var shareUrl = function (url, title, description, sceneType, transaction) {
    if (!cc.sys.isNative)return;
    if (getNativeVersion() < '1.4.0') {
        if (cc.sys.os == cc.sys.OS_IOS) {
            jsb.reflection.callStaticMethod(
                "AppController",
                "shareUrl:title:description:sceneType:",
                url,
                title,
                description,
                (sceneType ? 1 : 0)
            );
        }
        else {
            jsb.reflection.callStaticMethod(
                "org/cocos2dx/javascript/AppActivity",
                "shareUrl",
                "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZLjava/lang/String;)V",
                url,
                title,
                description,
                (sceneType ? true : false),
                transaction
            );
        }
    } else {
        WXUtils.shareUrl(url, title, description, sceneType, transaction);
    }
};

var checkAllNodesValid = function (node) {
    if (!cc.sys.isObjectValid(node))
        return false;
    var children = node.getChildren();
    if (children.length) {
        for (var i = 0; i < children.length; i++)
            if (!checkAllNodesValid(children[i]))
                return false;
    }
    return true;
};

var getTransResult = function (key) {
    if (!cc.sys.isNative)
        return;

    if (cc.sys.os == cc.sys.OS_IOS) {
        return jsb.reflection.callStaticMethod(
            "AppController",
            "getTransResult:",
            key
        );
    }
    else {
        return jsb.reflection.callStaticMethod(
            "org/cocos2dx/javascript/AppActivity",
            "getTransResult",
            "(Ljava/lang/String;)Ljava/lang/String;",
            key
        );
    }
};

var isFileOpened = function (filename) {
    if (!cc.sys.isNative)
        return;

    if (cc.sys.os == cc.sys.OS_IOS) {
        jsb.reflection.callStaticMethod(
            "AppController",
            "isFileOpened:",
            jsb.fileUtils.getWritablePath() + filename
        );
    }
    else {
        return jsb.reflection.callStaticMethod(
            "org/cocos2dx/javascript/AppActivity",
            "isFileOpened",
            "(Ljava/lang/String;)Z",
            filename
        );
    }
};

var startVoiceRecord = function (filename) {
    if (!cc.sys.isNative)
        return;

    if (!_.isUndefined(window.musicID)) {
        jsb.AudioEngine.pause(window.musicID);
    }

    if (cc.sys.os == cc.sys.OS_IOS) {
        jsb.reflection.callStaticMethod(
            "AppController",
            "startVoiceRecord:",
            jsb.fileUtils.getWritablePath() + filename
        );
    }
    else {
        jsb.reflection.callStaticMethod(
            "org/cocos2dx/javascript/AppActivity",
            "startVoiceRecord",
            "(Ljava/lang/String;)V",
            filename
        );
    }
};

var stopVoiceRecord = function (filename) {
    if (!cc.sys.isNative)
        return;
    if (!_.isUndefined(window.musicID)) {
        jsb.AudioEngine.resume(window.musicID);
    }

    if (cc.sys.os == cc.sys.OS_IOS) {
        jsb.reflection.callStaticMethod(
            "AppController",
            "stopVoiceRecord:",
            jsb.fileUtils.getWritablePath() + filename
        );
    }
    else {
        jsb.reflection.callStaticMethod(
            "org/cocos2dx/javascript/AppActivity",
            "stopVoiceRecord",
            "(Ljava/lang/String;)V",
            filename
        );
    }
};

var playVoiceByUrl = function (url) {
    if (!cc.sys.isNative)
        return;

    if (cc.sys.os == cc.sys.OS_IOS) {
        jsb.reflection.callStaticMethod(
            "AppController",
            "playVoiceByUrl:",
            url
        );
    }
    else {
        jsb.reflection.callStaticMethod(
            "org/cocos2dx/javascript/AppActivity",
            "playVoiceByUrl",
            "(Ljava/lang/String;)V",
            url
        );
    }
};

var uploadFileToOSS = function (readFilename, uploadFilename, cbSucc, cbFail) {
    if (!cc.sys.isNative)
        return;

    var filePath = jsb.fileUtils.getWritablePath() + readFilename;

    if (jsb.fileUtils.isFileExist(filePath)) {
        var data = jsb.fileUtils.getDataFromFile(filePath);

        var accessid = ALOV[gameData.appId][2];
        var arr = ALOV[gameData.appId][3];
        var host = ALOV[gameData.appId][1];
        var subdir = ALOV[gameData.appId][4] || "";
        var url = host + "/" + subdir + uploadFilename;

        var flag = false;
        var xhr = cc.loader.getXMLHttpRequest();
        xhr.open("PUT", url);
        xhr.setRequestHeader("Content-Length", data.length);
        var date = new Date().toGMTString();
        var contentMd5 = '';
        var contentType = 'application/x-www-form-urlencoded';
        var canonicalizedOSSHeaders = '';
        var canonicalizedResource = '/' + ALOV[gameData.appId][0] + '/' + subdir + uploadFilename;
        var authStr = "PUT\n"
            + contentMd5 + "\n"
            + contentType + "\n"
            + date + "\n"
            + canonicalizedOSSHeaders
            + canonicalizedResource;
        var auth = Crypto.util.bytesToBase64(Crypto.HMAC(Crypto.SHA1, authStr, arr.join(''), {asBytes: true}));
        xhr.setRequestHeader("Date", date);
        xhr.setRequestHeader("Content-Type", contentType);
        xhr.setRequestHeader("Authorization", "OSS " + accessid + ":" + auth);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    console.log("success");
                    if (cbSucc)
                        cbSucc(url);
                }
                else {
                    console.log(xhr.responseText);
                    if (!flag) {
                        flag = true;
                        if (cbFail)
                            cbFail(xhr.statusText, xhr.responseText);
                    }
                }
            }
        };
        xhr.onerror = function () {
            console.log("error");
            if (!flag) {
                flag = true;
                if (cbFail)
                    cbFail(xhr.status, null);
            }
        };
        xhr.send(data);
    }
};

var httpGet = function (url, cbSucc, cbFail) {
    cc.log(url);
    var flag = false;
    var xhr = cc.loader.getXMLHttpRequest();
    xhr.open("GET", url);
    if (cc.sys.isNative) {
        xhr.setRequestHeader("Accept-Encoding", "gzip,deflate");
    }
    // xhr.setRequestHeader("User-Agent", "curl/7.27.0");
    // xhr.setRequestHeader("Accept-Encoding", "gzip, deflate");
    // xhr.setRequestHeader("Accept-Encoding", "deflate");
    // xhr.setRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36");
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                // cc.log(xhr.responseText);
                cbSucc(xhr.responseText);
            }
            else {
                if (!flag) {
                    flag = true;
                    cbFail(xhr.statusText, xhr.responseText);
                }
            }
        }
    };
    xhr.onerror = function () {
        if (!flag) {
            flag = true;
            cbFail(xhr.status, null);
        }
    };
    xhr.send();
};

var httpPost = function (url, data, ajaxSuccess, ajaxError) {
    data = _.isString(data) ? data : JSON.stringify(data);
    var xhr = cc.loader.getXMLHttpRequest();
    xhr.open("POST", url);
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    // xhr.setRequestHeader("Content-Length", data.length);
    xhr.onreadystatechange = function () {
        var result, error = false;
        if (xhr.readyState == 4) {
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || xhr.status == 0) {
                var dataType = xhr.getResponseHeader('content-type');
                result = xhr.responseText;
                cc.log(result);
                try {
                    if (dataType.indexOf('json')) result = JSON.parse(result);
                } catch (e) {
                    error = e
                }

                if (error) ajaxError(error, 'parsererror', xhr);
                else ajaxSuccess(result, xhr)
            } else {
                ajaxError(xhr.statusText || null, xhr.status ? 'error' : 'abort', xhr)
            }
        }
    };
    xhr.onerror = function () {
        ajaxError(xhr.statusText || null);
    };
    xhr.send(Base64.encode(data));
};

var create$ = function (sceneNode) {
    var func = function (query, rootNode) {
        var arr = query.split(/\./g);
        var t = rootNode || sceneNode;
        for (var i = 0; i < arr.length; i++)
            if (t) {
                if (!cc.sys.isObjectValid(t)) {
                    cc.log("-- not a valid object " + query);
                    return null;
                }
                t = t.getChildByName(arr[i]);
            }
            else {
                return null;
            }
        return t;
    };
    var retFunc = null;
    if (_.isArray(sceneNode)) {
        retFunc = function (query, rootNode) {
            if (rootNode)
                return func(query, rootNode);
            else {
                for (var i = 0; i < sceneNode.length; i++) {
                    var ret = func(query, sceneNode[i]);
                    if (ret)
                        return ret;
                }
                return null;
            }
        };
    }
    else
        retFunc = func;
    retFunc.get = httpGet;
    retFunc.post = httpPost;
    return retFunc;
};

var duplicateSprite = function (sprite, isCopyUserdata) {
    var newSprite = null;
    if (sprite instanceof cc.Sprite) {
        newSprite = new cc.Sprite(sprite.getSpriteFrame());
        newSprite.setBlendFunc(sprite.getBlendFunc());
    }
    else if (sprite instanceof ccui.CheckBox) {
        if (cc.sys.isNative)
            newSprite = sprite.clone();
        else {
            newSprite = new ccui.CheckBox();
            newSprite._copySpecialProperties(sprite);
        }
    }
    else if (sprite instanceof ccui.Text) {
        //newSprite = sprite.clone();
        newSprite = new ccui.Text();
        newSprite.setFontName(newSprite.getFontName());
        newSprite.setTextColor(sprite.getTextColor());
        newSprite.setFontSize(sprite.getFontSize());
        newSprite.setTextHorizontalAlignment(sprite.getTextHorizontalAlignment());
        newSprite.setTextVerticalAlignment(sprite.getTextVerticalAlignment());
    } else if (sprite instanceof ccui.ImageView) {
        newSprite = sprite.clone();
        return newSprite;
    }
    else if (sprite instanceof ccui.Layout) {
        newSprite = sprite.clone();
        return newSprite;
    }
    else if (sprite instanceof ccui.TextAtlas) {
        newSprite = sprite.clone();
        newSprite.setString(sprite.getString());
        return newSprite;
    }
    newSprite.setAnchorPoint(sprite.getAnchorPoint());
    newSprite.setScale(sprite.getScaleX(), sprite.getScaleY());
    newSprite.setPosition(sprite.getPosition());
    newSprite.setContentSize(sprite.getContentSize());
    newSprite.setColor(sprite.getColor());
    newSprite.setOpacity(sprite.getOpacity());
    newSprite.setVisible(sprite.isVisible());
    newSprite.setName(sprite.getName());
    if (sprite instanceof cc.Sprite) {
        var children = sprite.getChildren();
        for (var i = 0; i < children.length; i++) {
            var child = children[i];
            var dname = child.getName();
            if (dname != 'hulayout' && dname != 'hutiparrow' && dname != 'hucardSprite' && dname != 'hutipsprite') {
                var node = duplicateSprite(child, true);
                newSprite.addChild(node);
            }

        }
    }

    if (isCopyUserdata)
        newSprite.setUserData(_.clone(sprite.getUserData()));
    return newSprite;
};
var getCurrentTimeMills = function () {
    var date = new Date();
    var yy = date.getYear();
    var MM = date.getMonth() + 1;
    var dd = date.getDay();
    var hh = date.getHours();
    var mm = date.getMinutes();
    var ss = date.getSeconds();
    var sss = date.getMilliseconds();
    return Date.UTC(yy, MM, dd, hh, mm, ss, sss);
};

var duplicateOnlyNewLayer = function (layout) {
    var newLayout = null;
    newLayout = new ccui.Layout();
    newLayout.setSize(layout.getSize());
    newLayout.setLayoutType(layout.getLayoutType());
    newLayout.setBackGroundColorType(layout.getBackGroundColorType());
    newLayout.setBackGroundColor(layout.getBackGroundColor());
    newLayout.setBackGroundColorOpacity(layout.getBackGroundColorOpacity());
    var children = layout.getChildren();
    for (var i = 0; i < children.length; i++) {
        var node = duplicateSprite(children[i], true);
        newLayout.addChild(node);
    }
    return newLayout;
}
var popHideAni = function(layer, func){
    layer.runAction(cc.sequence(
        cc.scaleTo(0.2, 0),
        cc.callFunc(function(){
            var parent = layer.getParent();
            if(parent) {
                var mask = parent.getChildByName('mask');
                if (mask) {
                    mask.runAction(cc.sequence(
                        cc.scaleTo(0.1, 0),
                        cc.removeSelf()
                    ));
                }
            }
            func();
        })
    ));
}
var numberTo6CharString = function (val) {
    var ret = '';
    if(val!=undefined && _.isNumber(val)){
        ret += val;
        for(var i=0; i<6,ret.length<6; i++){
            ret = '0' + ret;
        }
        return ret;
    }
    return '';
}
var popShowAni = function(layer, noMask){
    if(!noMask) {
        //加背景蒙版
        var mask = new cc.LayerColor(cc.color(0, 0, 0, 255 / 2), cc.winSize.width, cc.winSize.height);
        mask.setName('mask');
        mask.setPosition(0, 0);
        layer.getParent().addChild(mask, -1);

        var chupaiListener = cc.EventListener.create({
            event: cc.EventListener.TOUCH_ONE_BY_ONE,
            swallowTouches: true,
            onTouchBegan: function (touch, _) {
                return true;
            },
            onTouchMoved: function (touch, _) {
            },
            onTouchEnded: function (touch, _) {
            }
        });
        cc.eventManager.addListener(chupaiListener, mask);
    }

    layer.setScale(0);
    layer.runAction(cc.sequence(
        cc.scaleTo(0.1, 1.05, 1.05),
        cc.scaleTo(0.08, 0.95, 0.95),
        // cc.scaleTo(0.05, 0.95, 1.05),
        cc.scaleTo(0.05, 1, 1)
    ));
}
var duplicateLayout = function (layout) {
    var newLayout = null;
    if (layout instanceof cc.Sprite)
        newLayout = duplicateSprite(layout);
    else if (layout instanceof ccui.Layout) {
        newLayout = layout.clone();
        //newLayout = new ccui.Layout();
        //newLayout.setSize(layout.getSize());
        //newLayout.setLayoutType(layout.getLayoutType());
        //newLayout.setBackGroundColorType(layout.getBackGroundColorType());
        //newLayout.setBackGroundColor(layout.getBackGroundColor());
        //newLayout.setBackGroundColorOpacity(layout.getBackGroundColorOpacity());
    }
    else if (layout instanceof cc.Node)
        newLayout = new cc.Node();
    newLayout.setPosition(layout.getPosition());
    newLayout.setScale(layout.getScale());
    newLayout.setAnchorPoint(layout.getAnchorPoint());
    newLayout.setOpacity(255);
    newLayout.setVisible(true);
    var children = layout.getChildren();
    for (var i = 0; i < children.length; i++) {
        var node = duplicateSprite(children[i], true);
        newLayout.addChild(node);
    }
    return newLayout;
};
function tableViewRefresh(tableView){
    if(tableView != null){
        var content = tableView.getContainer();
        var posy = content.getPositionY();
        tableView.reloadData();

        var viewSize = tableView.getViewSize();
        if(posy == viewSize.height)
            return;

        var baseY = 0;
        var size = content.getContentSize();
        if(size.height < viewSize.height){
            baseY = viewSize.height - size.height;
        }
        if(posy > baseY)posy = baseY;

        var topY = viewSize.height - size.height;
        if(posy < topY)posy = topY;

        content.setPositionY(posy);
        tableView.scrollViewDidScroll(tableView);
    }
}

var loadImageToSprite2 = function (url, targetSprite) {
    if (url.charAt(url.length - 2) == '/' &&
        url.charAt(url.length - 1) == '0')
        url = url.substr(0, url.length - 2) + '/132';

    var userData = targetSprite.getUserData() || {};
    if (userData.url == url)
        return;

    var sprite = null;
    var children = targetSprite.getChildren();
    for (var i = 0; i < children.length; i++) {
        var child = children[i];
        if (child.getName() == 'head') {
            sprite = child;
            break;
        }
    }

    if (sprite)
        sprite.setTexture(cc.textureCache.addImage('res/ui/resources/transparent/transparent.png'));
    if (!url)
        return;

    cc.textureCache.addImageAsync(url, function (texture) {
        if (!sprite)
            sprite = new cc.Sprite(texture);
        sprite.setTexture(texture);

        var scaleX = targetSprite.getContentSize().width / sprite.getContentSize().width;
        var scaleY = targetSprite.getContentSize().height / sprite.getContentSize().height;
        sprite.setScale(scaleX, scaleY);
        sprite.setAnchorPoint(0, 0);
        sprite.setName('head');
        if (!targetSprite.getChildByName('head'))
            targetSprite.addChild(sprite);

        userData.url = url;
        targetSprite.setUserData(userData);
    }, null);
};
var showLoading = function (content) {
    cc.sys.isObjectValid(cc.director.getRunningScene()) && cc.director.getRunningScene().scheduleOnce(function () {
        var loadingLayer = cc.director.getRunningScene().getChildByName('loading');
        if (!loadingLayer) {
            loadingLayer = new LoadingLayer();
            loadingLayer.setName("loading");
            cc.director.getRunningScene().addChild(loadingLayer, 1000);
        }
        loadingLayer.setContent(content);
        loadingLayer.setVisible(true);
    }, 0);
};

var hideLoading = function () {
    cc.sys.isObjectValid(cc.director.getRunningScene()) && cc.director.getRunningScene().scheduleOnce(function () {
        var loadingLayer = cc.director.getRunningScene().getChildByName('loading');
        if (loadingLayer) {
            loadingLayer.setVisible(false);
        }
    }, 0);
};

// var setTimeout = function (func, time) {
//     cc.sys.isObjectValid(cc.director.getRunningScene()) && cc.director.getRunningScene().scheduleOnce(function () {
//         func();
//     }, time / 1000.0);
// };

// var setInterval = function (func, time) {
//     cc.sys.isObjectValid(cc.director.getRunningScene()) && cc.director.getRunningScene().schedule(function () {
//         func();
//     }, time / 1000.0, cc.REPEAT_FOREVER);
// };

var alert0 = function (title, content, isAutoHideLoading) {
    isAutoHideLoading = _.isUndefined(isAutoHideLoading) ? true : isAutoHideLoading;
    if (isAutoHideLoading)
        hideLoading();
    cc.sys.isObjectValid(cc.director.getRunningScene()) && cc.director.getRunningScene().scheduleOnce(function () {
        var tishiLayer = new TishiLayer('alert0', title, content, null, null, true);
        cc.director.getRunningScene().addChild(tishiLayer, 1000);
    }, 0);
};

var alert1 = function (content, onOk, canCancel, isAutoHideLoading, isHCenter, isVCenter) {
    isAutoHideLoading = _.isUndefined(isAutoHideLoading) ? true : isAutoHideLoading;
    if (isAutoHideLoading)
        hideLoading();
    cc.director.getRunningScene().scheduleOnce(function () {
        var tishiLayer = new TishiLayer('alert1', '提示', content, function () {
            if (onOk)
                onOk();
        }, null, !!canCancel, isHCenter, isVCenter, null, null);
        cc.director.getRunningScene().addChild(tishiLayer, 1000);
    }, 0);
};

var alert2 = function (content, onOk, onCancel, canCancel, isAutoHideLoading, isHCenter, isVCenter) {
    isAutoHideLoading = _.isUndefined(isAutoHideLoading) ? true : isAutoHideLoading;
    if (isAutoHideLoading)
        hideLoading();
    cc.sys.isObjectValid(cc.director.getRunningScene()) && cc.director.getRunningScene().scheduleOnce(function () {
        var tishiLayer = new TishiLayer('alert2', '提示', content, function () {
            if (onOk)
                onOk();
        }, function () {
            if (onCancel)
                onCancel();
        }, !!canCancel, isAutoHideLoading, isHCenter, isVCenter);
        cc.director.getRunningScene().addChild(tishiLayer, 1000);
    }, 0);
};

var preloadMascene1 = function () {
    window.ccsCache = window.ccsCache || {};
    // if (window.ccsCache[res.MaScene1_json]) {
    //     window.ccsCache[res.MaScene1_json].release();
    //     delete window.ccsCache[res.MaScene1_json];
    // }
    if (!window.ccsCache[res.MaScene1_json]) {
        window.ccsCache[res.MaScene1_json] = ccs.load(res.MaScene1_json).node;
        window.ccsCache[res.MaScene1_json].retain();
    }
};

var addCachedCCSChildrenTo = function (res, distNode) {
    var isRelease = !!window.ccsCache[res];
    window.ccsCache[res] = window.ccsCache[res] || ccs.load(res).node;
    var parent = window.ccsCache[res];
    var arr = [];
    for (var i = 0; i < parent.children.length; i++)
        arr.push(parent.children[i]);
    for (var i = 0; i < arr.length; i++) {
        arr[i].retain();
        arr[i].removeFromParent(false);
    }
    for (var i = 0; i < arr.length; i++) {
        distNode.getChildByName("Scene").addChild(arr[i]);
        arr[i].release();
    }
    if (isRelease)
        window.ccsCache[res].release();
    delete window.ccsCache[res];
};

var batchSetChildrenZorder = function (node, map) {
    for (var k in map)
        if (map.hasOwnProperty(k)) {
            var child = node.getChildByName(k);
            if (child)
                child.setLocalZOrder(map[k]);
        }
};

var loadCCSTo = function (res, distNode, rootName, moreArr, playaction) {
    moreArr = moreArr || [];
    var mainscene = null;
    if (window.ccsCache && window.ccsCache[res]) {
        mainscene = window.ccsCache[res];
        window.ccsCache[res] = null;
        distNode.addChild(mainscene.node);
        mainscene.node.release();
    }
    else {
        mainscene = ccs.load(res);
        distNode.addChild(mainscene.node);
    }

    var interval = null;
    var checkFunc = function () {
        if (!checkAllNodesValid(distNode.getChildByName(rootName)))
            return;
        var rootNode = distNode.getChildByName(rootName);
        for (var i = 0; i < moreArr.length; i++) {
            var node = rootNode.getChildByName(moreArr[i]);
            if (!node || !cc.sys.isObjectValid(node))
                return;
        }
        clearInterval(interval);
        interval = null;

        var ret = true;
        if (distNode.getBeforeOnCCSLoadFinish && distNode.getBeforeOnCCSLoadFinish())
            ret = distNode.getBeforeOnCCSLoadFinish()();
        if (ret && distNode.onCCSLoadFinish)
            distNode.onCCSLoadFinish.call(distNode);
    };
    interval = setInterval(checkFunc, 1);
    checkFunc();
    if (playaction) {
        mainscene.node.runAction(mainscene.action);
        mainscene.action.play('action', true);
    }
};

var crash = function () {
    if (cc.sys.os == cc.sys.OS_IOS) {
        jsb.reflection.callStaticMethod(
            "AppController",
            "crash"
        );
    }
    else {
        jsb.reflection.callStaticMethod(
            "org/cocos2dx/javascript/AppActivity",
            "crash",
            "(Z)V",
            true
        );
    }
};

var calcPos = function (edgeWidth, partWidth, intervalWidth, num, cb) {
    //var left = totalWidth - (num - 1) * intervalWidth - edgeWidth * num;
    for (var i = 0; i < num; i++) {
        cb(i, edgeWidth + partWidth * i + intervalWidth * i);
    }
};
var loadCircleConorToSprite = function (url, headBg, r, w_off, h_off, x_off, y_off) {
    var headBgScaleBak = headBg.getScale();
    headBg.setScale(1);
    w_off = w_off || 0;
    h_off = h_off || 0;
    x_off = x_off || 0;
    y_off = y_off || 0;
    r = r || 6;

    var clipNode = headBg.getChildByName("head_clip");
    if (!clipNode) {
        var headBgBoundingBox = headBg.getBoundingBox();
        var headBgSize = cc.size(headBgBoundingBox.width, headBgBoundingBox.height);
        var clipNodeSize = cc.size(headBgSize.width, headBgSize.height);
        clipNode = cc.ClippingNode.createRoundRect(headBgSize.width + w_off, headBgSize.height + h_off, r);
        clipNode.setScale(clipNodeSize.width / headBgSize.width);
        clipNode.setPosition(x_off - w_off / 2, y_off - h_off / 2);
        clipNode.setName('head_clip');
        headBg.addChild(clipNode);
    }

    headBg.setScale(headBgScaleBak);

    var head = clipNode.getChildByName('head');
    if (head)
        head.removeFromParent(true);
    head = new cc.Sprite(headBg.getTexture());
    head.setAnchorPoint(0, 0);
    head.setName('head');
    // head.hide();
    head.setVisible(false);
    clipNode.addChild(head);
    if (url.startsWith('res/')) {
        head.setTexture(cc.textureCache.addImage(url));
        head.setVisible(true);
    } else {
        NetUtils.downloadHeadImgToSprite(url, head, function () {
            head.setVisible(true);
        });
    }

}
var loadImageToSprite = function (url, targetSprite) {
    if (url == "" || url == null||url.length<10)
        return;
    if (url.charAt(url.length - 2) == '/' &&
        url.charAt(url.length - 1) == '0')
        url = url.substr(0, url.length - 2) + '/132';

    var userData = targetSprite.getUserData() || {};
    if (userData.url == url)
        return;

    var sprite = null;
    var children = targetSprite.getChildren();
    for (var i = 0; i < children.length; i++) {
        var child = children[i];
        if (child.getName() == 'head') {
            sprite = child;
            break;
        }
    }

    if (sprite)
        sprite.setTexture(cc.textureCache.addImage('res/ui/resources/transparent/transparent.png'));
    if (!url)
        return;
    cc.textureCache.addImageAsync(url, function (texture) {
        if (!sprite)
            sprite = new cc.Sprite(texture);
        sprite.setTexture(texture);

        var scaleX = targetSprite.getContentSize().width / sprite.getContentSize().width;
        var scaleY = targetSprite.getContentSize().height / sprite.getContentSize().height;
        sprite.setScale(scaleX, scaleY);
        sprite.setAnchorPoint(0, 0);
        sprite.setName('head');
        if (!targetSprite.getChildByName('head'))
            targetSprite.addChild(sprite);

        userData.url = url;
        targetSprite.setUserData(userData);
    }, null);
};

var getPositionRelativeToParent = function (node, level) {
    var t = node;
    var a = 0, b = 0;
    for (var i = 0; i < level; i++) {
        if (!t)
            return null;
        a += t.getPositionX();
        b += t.getPositionY();
        t = t.getParent();
    }
    if (t) {
        return cc.p(a, b);
    }
    return null;
};

var getPositionRelativeToSibling = function (node, sibling) {
    var p0 = node.getPosition();
    var p1 = sibling.getPosition();
    p0.x -= p1.x;
    p0.y -= p1.y;
    return p0;
};

var getSortFlag = function () {
    var flag = 1;
    var sortFlag = cc.sys.localStorage.getItem('sortFlag');
    if (sortFlag) {
        flag = parseInt(sortFlag);
    }
    return flag;
};
var deepCopy = function (source) {
    var result;
    if (_.isArray(source)) {
        result = [];
        for (var i = 0; i < source.length; i++)
            result.push(typeof source[i] === 'object' ? deepCopy(source[i]) : source[i])
    } else {
        result = {};
        for (var key in source) {
            if (source.hasOwnProperty(key))
                result[key] = typeof source[key] === 'object' ? deepCopy(source[key]) : source[key];
        }
    }
    return result;
};
var UTF8ArrayToUTF16Array = function (s) {
    if (!s)
        return;
    var i, codes, bytes, ret = [], len = s.length;
    for (i = 0; i < len; i++) {
        codes = [];
        codes.push(s[i]);
        if (((codes[0] >> 7) & 0xff) == 0x0) {
            //单字节  0xxxxxxx
            ret.push(s[i]);
        } else if (((codes[0] >> 5) & 0xff) == 0x6) {
            //双字节  110xxxxx 10xxxxxx
            codes.push(s[++i]);
            bytes = [];
            bytes.push(codes[0] & 0x1f);
            bytes.push(codes[1] & 0x3f);
            ret.push((bytes[0] << 6) | bytes[1]);
        } else if (((codes[0] >> 4) & 0xff) == 0xe) {
            //三字节  1110xxxx 10xxxxxx 10xxxxxx
            codes.push(s[++i]);
            codes.push(s[++i]);
            bytes = [];
            bytes.push((codes[0] << 4) | ((codes[1] >> 2) & 0xf));
            bytes.push(((codes[1] & 0x3) << 6) | (codes[2] & 0x3f));
            ret.push((bytes[0] << 8) | bytes[1]);
        }
    }
    return ret;
};

var track_idx = 0;
var createSp = function (res_name) {
    if (!res['sp_' + res_name + '_json'] || !res['sp_' + res_name + '_atlas']) {
        cc.log("spine files not exist, res_name = " + res_name);
        return null;
    }
    return new sp.SkeletonAnimation(res['sp_' + res_name + '_json'], res['sp_' + res_name + '_atlas']);
};
var playSpAnimation = function (sp_anim, animation_name, isLoop) {
    if (typeof sp_anim === 'string') {
        sp_anim = createSp(sp_anim);
    }
    if (sp_anim instanceof sp.SkeletonAnimation) {
        sp_anim.setAnimation(track_idx++,
            _.isUndefined(animation_name) ? 'animation' : animation_name,
            _.isUndefined(isLoop) ? true : isLoop);
        return sp_anim;
    }
    return null;
};

var lightButton = function (sprite, x, y, stencil) {
    if (sprite && sprite instanceof cc.Sprite) {
        if (sprite.getParent().getChildByName(sprite.getName() + '_clipnode')) {
            return;
        }
        if (!stencil) {
            stencil = res.Btn_stencil_png;
        }
        var offx = x || 0;
        var offy = y || 0;
        var clip = new cc.ClippingNode();
        var gameTitle = new cc.Sprite(stencil);
        clip.setStencil(gameTitle);
        clip.setAlphaThreshold(0);
        clip.setContentSize(cc.size(gameTitle.getContentSize().width, gameTitle.getContentSize().height));
        var clipSize = clip.getContentSize();
        clip.setPosition(cc.p(sprite.getPositionX() + offx, sprite.getPositionY() + offy));

        var spark = new cc.Sprite(res.ButtonLight_png);
        spark.setPosition(cc.p(-clipSize.width / 2, 0));
        clip.addChild(spark, 2);
        clip.setName(sprite.getName() + '_clipnode');
        sprite.getParent().addChild(clip, 4);

        var moveAction = cc.moveTo(2.6, cc.p(clipSize.width, 0));
        var moveBack = cc.moveTo(0, cc.p(-clipSize.width, 0));
        var seq = cc.sequence(moveAction, moveBack);
        var repreatAction = cc.repeatForever(seq);
        spark.runAction(repreatAction);
    }
};
var getCurTimeMillisecond = function () {
    return Math.round((new Date()).getTime());
};
var removeLightButton = function (sprite) {
    if (sprite && sprite instanceof cc.Sprite) {
        var clipnode = sprite.getParent().getChildByName(sprite.getName() + '_clipnode');
        if (clipnode) {
            clipnode.removeFromParent();
        }
    }
};

/**
 * approx distance between two points on earth ellipsoid
 * @param {Object} lat1
 * @param {Object} lng1
 * @param {Object} lat2
 * @param {Object} lng2
 */
var EARTH_RADIUS = 6378137.0;    //单位M
var PI = Math.PI;
function getRad(d) {
    return d * PI / 180.0;
}
function getFlatternDistance(lat1, lng1, lat2, lng2) {
    lat1 = parseFloat(lat1);
    lng1 = parseFloat(lng1);
    lat2 = parseFloat(lat2);
    lng2 = parseFloat(lng2);
    var f = getRad((lat1 + lat2) / 2);
    var g = getRad((lat1 - lat2) / 2);
    var l = getRad((lng1 - lng2) / 2);

    var sg = Math.sin(g);
    var sl = Math.sin(l);
    var sf = Math.sin(f);

    var s, c, w, r, d, h1, h2;
    var a = EARTH_RADIUS;
    var fl = 1 / 298.257;

    sg = sg * sg;
    sl = sl * sl;
    sf = sf * sf;

    s = sg * (1 - sl) + (1 - sf) * sl;
    c = (1 - sg) * (1 - sl) + sf * sl;

    w = Math.atan(Math.sqrt(s / c));
    r = Math.sqrt(s * c) / w;
    d = 2 * w * a;
    h1 = (3 * r - 1) / 2 / c;
    h2 = (3 * r + 1) / 2 / s;

    var ret = d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg));
    return _.isNaN(ret) ? 0 : ret.toFixed(1);
}

var showToast = function (str) {
    if (!_.isUndefined(str) && (typeof str == 'string' || typeof str == 'number') && str != '') {
        var scale9Sprite = new cc.Scale9Sprite(res.chatroom_input_back, cc.rect(0, 0, 78, 36), cc.rect(20, 15, 38, 3));
        scale9Sprite.setAnchorPoint(cc.p(0.5, 0.5));
        scale9Sprite.setPosition(cc.p(cc.winSize.width / 2, cc.winSize.height * 3 / 4));
        var text = new ccui.Text();
        text.setFontSize(40);
        text.setTextColor(cc.color(255, 213, 136));
        text.setString(str);
        scale9Sprite.addChild(text);
        scale9Sprite.setContentSize(cc.size(text.getContentSize().width + 30, text.getContentSize().height + 20));
        text.setPosition(cc.p(scale9Sprite.getContentSize().width / 2, scale9Sprite.getContentSize().height / 2));
        cc.director.getRunningScene().addChild(scale9Sprite);
        scale9Sprite.setScale(0.7);
        scale9Sprite.runAction(cc.sequence(
            cc.scaleTo(0.05, 1.1),
            cc.scaleTo(0.02, 1),
            cc.delayTime(1.5),
            cc.spawn(
                cc.moveBy(0.8, cc.p(0, 100)),
                cc.fadeOut(0.8)
            ),
            cc.callFunc(function () {
                scale9Sprite.removeFromParent(true);
            })
        ));
    }
};

var getPaiNameById = function (id) {
    if (id >= 0 && id <= 12) return ["b/red_" + (id - 0) % 13 + ".png", "b/bigtag_2.png"];
    if (id >= 39 && id <= 51) return ["b/red_" + (id - 39) % 13 + ".png", "b/bigtag_0.png"];
    if (id >= 13 && id <= 25) return ["b/black_" + (id - 13) % 13 + ".png", "b/bigtag_3.png"];
    if (id >= 26 && id <= 38) return ["b/black_" + (id - 26) % 13 + ".png", "b/bigtag_1.png"];
    if (id == 52) return ["b/smalltag_4.png"];
    if (id == 53) return ["b/smalltag_5.png"];
};
//牛牛 红桃0-12 黑桃13-25 梅花26-38 方片39-51   后端给的数据  1-4 A 5-8 2  //1方片 2梅花 3红桃 4黑桃
var getPaiNameByIdNN = function (id) {
    var color = (id - 1) % 4;
    var value = Math.floor((id - 1) / 4);
    var cardAdd = [39, 26, 0, 13];
    var card = cardAdd[color] + value;
    return "poker_" + card + ".png";
};
/**
 * 数字转换 例如1转①
 * @param txtstring 数字
 * @returns {string} 转换后的数字
 */
var ToDBC = function (txtstring) {
    var tmp = "";
    if (typeof txtstring != 'string') {
        txtstring = "" + txtstring;
    }
    for (var i = 0; i < txtstring.length; i++) {
        if (txtstring.charCodeAt(i) == 32) {
            tmp = tmp + String.fromCharCode(12288);
        }
        if (txtstring.charCodeAt(i) < 127) {
            tmp = tmp + String.fromCharCode(txtstring.charCodeAt(i) + 65248);
        }
    }
    return tmp;
};
/**
 * @returns {bool} 是否联网
 */
var isNetwork = function () {
    if (cc.sys.os == cc.sys.OS_IOS) {
        return jsb.reflection.callStaticMethod("NetManager", "isNetwork");
    } else if (cc.sys.os == cc.sys.OS_ANDROID) {
        return jsb.reflection.callStaticMethod(packageUri + "/utils/NetManager", "isNetwork", "()Z");
    }
};
/**
 * @returns {bool} 是否是wifi
 */
var isWifi = function () {
    if (cc.sys.os == cc.sys.OS_IOS) {
        return jsb.reflection.callStaticMethod("NetManager", "isWifi");
    } else if (cc.sys.os == cc.sys.OS_ANDROID) {
        return jsb.reflection.callStaticMethod(packageUri + "/utils/NetManager", "isWifi", "()Z");
    }
};
/**
 * @returns {bool} 是否是wifi
 */
var isWAN = function () {
    if (cc.sys.os == cc.sys.OS_IOS) {
        return jsb.reflection.callStaticMethod("NetManager", "isWAN");
    } else if (cc.sys.os == cc.sys.OS_ANDROID) {
        return jsb.reflection.callStaticMethod(packageUri + "/utils/NetManager", "isWAN", "()Z");
    }
};
/**
 * 开启网络监听
 */
var beginNetListener = function () {
    if (cc.sys.os == cc.sys.OS_IOS) {
        jsb.reflection.callStaticMethod("NetManager", "beginNetListener");
    } else if (cc.sys.os == cc.sys.OS_ANDROID) {
        jsb.reflection.callStaticMethod(packageUri + "/utils/NetManager", "beginNetListener", "()V");
    }
};
/**
 * 停止网络监听
 */
var stopNetListener = function () {
    if (cc.sys.os == cc.sys.OS_IOS) {
        jsb.reflection.callStaticMethod("NetManager", "stopNetListener");
    } else if (cc.sys.os == cc.sys.OS_ANDROID) {
        jsb.reflection.callStaticMethod(packageUri + "/utils/NetManager", "stopNetListener", "()V");
    }
};


var overwrite_cc_audioEngine_setMusicVolume = function () {
    var funcBak = cc.audioEngine.setMusicVolume;
    cc.audioEngine.setMusicVolume = function (vol) {
        // funcBak.call(cc.audioEngine, 0.1 * vol);
    };
};

var overwrite_cc_audioEngine_setEffectsVolume = function () {
    var funcBak = cc.audioEngine.setEffectsVolume;
    cc.audioEngine.setEffectsVolume = function (vol) {
        // funcBak.call(cc.audioEngine, 0.1 * vol);
    };
};

var isNiuniu = function () {
    if (gameData.mapId == MAP_ID_DN)
        return true;
    else
        return false;
};


overwrite_cc_audioEngine_setMusicVolume();
overwrite_cc_audioEngine_setEffectsVolume();